<?php
/**
 * 外部接口资源模型
 */

namespace app\models\common;

use think\Model;
use think\facade\Validate;

class OauthResourcesModel extends Model
{
    protected $table = 'oauth_resources';

    /**
     * 请求方式类型列表
     * @var array
     */
    private $methodTypeList = [
        'get' => 'GET',
        'post' => 'POST',
        'put' => 'PUT',
        'delete' => 'DELETE',
        'mqtt' => 'MQTT'
    ];

    /**
     * 获取数据记录列表
     * @param $param
     * @param $page
     * @return mixed
     */
    public function getRecordList(array $param = [], int $start = 0, int $size = 10)
    {
        $field = [
            'id',
            'name',
            'request_method',
            'path',
            'describe'
        ];

        $pdo = self::table($this->table)->field($field);
        $pdo = $this->createSearchParam($pdo, $param);
        if ($size > 0) {
            $pdo->limit($start, $size);
        }
        $list = $pdo->order('id desc')->select();
        $list = $list ? $list->toArray() : [];
        return $list;
    }

    /**
     * 获取记录数量
     * @param array $param
     * @return mixed
     */
    public function getRecordCount(array $param = [])
    {
        $pdo = self::table($this->table);
        $pdo = $this->createSearchParam($pdo, $param);
        return $pdo->count("*");
    }

    /**
     * 根据Id获取详细数据
     * @param $id
     * @return array
     */
    public function getInfoById($id, array $where = [])
    {
        $info = self::table($this->table)->where(['id' => $id])->find();
        $info = $info ? $info->toArray() : [];
        return $info;
    }


    /**
     * 获取请求方式列表
     * @return array
     * @date 2020-08-13 14:53
     */
    public function getMethodList()
    {
        return $this->methodTypeList;
    }

    /**
     * 创建数据记录
     * @param array $param
     * @return array
     */
    public function createRecord(array $param = [])
    {
        $res = $this->checkSaveData(0, $param);
        if ($res['status'] != STATUS_CODE_SUCCESS) return $res;
        $res = self::insertGetId($res['data']);
        if ($res === false) {
            return funReturn(STATUS_CODE_INSIDEERROR, '添加失败');
        }
        return funReturn(STATUS_CODE_SUCCESS, '添加成功', ['id' => $res]);
    }

    /**
     * 保存记录
     * @param $id
     * @param array $param
     * @return array
     */
    public function updateRecord($id, array $param = [])
    {
        $res = $this->checkSaveData($id, $param);
        if ($res['status'] != STATUS_CODE_SUCCESS) return $res;
        $res = self::where(['id' => $id])->update($res['data']);
        if ($res === false) {
            return funReturn(STATUS_CODE_INSIDEERROR, '保存失败');
        }
        return funReturn(STATUS_CODE_SUCCESS, '保存成功');
    }

    /**
     * 删除数据记录
     * @param $id
     * @return array
     */
    public function deleteRecord($id, array $where = [])
    {
        $res = self::where(['id' => $id])->delete();
        if ($res === false) {
            return funReturn(STATUS_CODE_INSIDEERROR, '删除失败');
        }
        return funReturn(STATUS_CODE_SUCCESS, '删除成功');
    }

    /**
     * 创建查询筛选条件
     * @param array $param
     * @param  $pdo
     */
    private function createSearchParam($pdo, array $param = [])
    {
        if (isset($param['keywords']) && (string)$param['keywords'] != '') {
            $pdo->where('name', 'like', "%{$param['keywords']}%");
        }
        if (isset($param['id']) && intval($param['id']) > 0) {
            $pdo->where('id', '=', $param['id']);
        }
        if (isset($param['ids'][0]) && is_array($param['ids'])) {
            $pdo->whereIn('id', $param['ids']);
        }
        return $pdo;

    }

    /**
     * 校验数据
     * @param $id
     * @param array $param
     * @return array
     */
    private function checkSaveData($id, array $param = [])
    {

        $rule = [
            'name' => 'require|max:60',
            'request_method' => 'require|in:get,post,put,delete,mqtt',
            'path' => 'require',
            'describe' => 'max:180',
        ];

        $message = [
            'name.require' => '名称必须',
            'name.max' => '名称最多60个字符',
            'request_method.require' => '请求类型必须',
            'path.require' => '资源路径必须',
            'describe.max' => '说明最多180个字符',
        ];
        $validate = Validate::message($message)->rule($rule);

        if (!$validate->check($param)) {
            return funReturn(STATUS_CODE_DATAERROR, $validate->getError());
        }
        $data = [
            'name' => $param['name'],
            'request_method' => $param['request_method'],
            'path' => $param['path'],
        ];
        if (isset($param['describe'])) $data['describe'] = $param['describe'];

        return funReturn(STATUS_CODE_SUCCESS, 'success', $data);

    }
}